import ViewLoading from '@/components/ViewLoading';
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { DomEditor } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
// import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { message } from 'antd';
import React, { useEffect, useState } from 'react';
import type { InsertFnType, YmRichEditorProps } from './interface';
import { OssUploadApi } from './utils/OssUploadFn';

const YmRichEditor: React.FC<YmRichEditorProps> = (props) => {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const {
    value,
    onChange,
    toolbarConfig = {},
    editorConfig = {},
    onEditorCreate,
    editorStyle = { height: '500px', overflowY: 'auto' },
    fileUploadConfig,
    mode = 'default',
  } = props;
  const [uploadLoading, setUploadLoading] = useState(false);

  // 工具栏配置
  // 工具栏是由一个个菜单组成的，工具栏的配置，就是配置 菜单的排序，分组，显示隐藏。
  const combineToolbarConfig: Partial<IToolbarConfig> = {
    excludeKeys: ['todo', 'group-video'], //
    ...toolbarConfig,
  };

  // 编辑器配置
  const combineEditorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        // 图片上传自定义
        customUpload(file: File, insertFn: InsertFnType) {
          const { dir, maxSize = 50, phone = 'default' } = fileUploadConfig;
          // 这里的file是对象，选择多张时customUpload会被调用多次
          if (file.size / 1024 / 1024 > maxSize) return message.error(`图片上大小不能超过${maxSize}M`);
          setUploadLoading(true);
          OssUploadApi.getOssUploadApiInstance()
            .ossUploadFn(file, dir, phone)!
            .then((res) => {
              // console.log('--richEditor--fileUpload--res--', res);
              if (res.res.status === 200) {
                const { name, url } = res; //name: "metting/1671618411472.png"  // url "http://logibeat-test.oss-cn-hangzhou.aliyuncs.com/metting/1671618411472.png"
                insertFn(url, file.name);
              } else {
                message.error('图片上传失败');
              }
            })
            .catch((err) => {
              console.log('--YmRichEditor--UploadImg--err--:', err);
            })
            .finally(() => {
              setUploadLoading(false);
            });
        },
      },
    },
    // readOnly:true   //编辑器只读
    // onCreated: (editor) => {} //编辑器创建完毕时的回调函数。
    // onChange:() => {} //编辑器内容、选区变化时的回调函数
    // onDestroyed:() => {} //编辑器销毁时的回调函数
    customAlert: (s: string, t: string) => {
      switch (t) {
        case 'success':
          message.success(s);
          break;
        case 'info':
          message.info(s);
          break;
        case 'warning':
          message.warning(s);
          break;
        case 'error':
          message.error(s);
          break;
        default:
          message.info(s);
          break;
      }
    },
    ...editorConfig,
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    if (editor) {
      // editor.setHtml();
      const toolbar = DomEditor.getToolbar(editor);
      const curToolbarConfig = toolbar && toolbar.getConfig();
      // console.log('--ymRichEditor--toolbarKeys---:', curToolbarConfig?.toolbarKeys); //  查看当前的默认菜单排序和分组配置
      // editor.getConfig().hoverbarKeys // hoverbar 菜单
    }
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  /**
   * 判断editor富文本域是否为空
   * str返回的值为"" 代表输入框里面有值 成功
   * str返回！="" 代表里面有空格 回车 失败
   * */
  const checkVal = (str: string) => {
    let num = 0;
    const reg = /<p>(&nbsp;|&nbsp;\s+)+<\/p>|<p>(<br>)+<\/p>/g;
    while (num < str.length && str != '') {
      num++;
      const k = str.match(reg);
      if (k) {
        str = str.replace(k[0], '');
      }
    }
    return str == '';
  };
  return (
    <>
      <ViewLoading show={uploadLoading} />
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={combineToolbarConfig}
          mode={mode}
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={combineEditorConfig}
          value={value}
          onCreated={(editorParam) => {
            setEditor(editorParam);
            onEditorCreate?.(editorParam);
          }}
          onChange={(editorParam) => {
            if (!checkVal(editorParam.getHtml())) {
              //有内容
              onChange?.(editorParam.getHtml());
            } else {
              //没内容 没内容的时候editorParam.getHtml()会返回"<p></n></p>"
              onChange?.('');
            }
          }}
          mode={mode}
          style={editorStyle}
        />
      </div>
    </>
  );
};

export default YmRichEditor;
